package com.asset.salesforce.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Invoice;
import com.asset.salesforce.domain.InvoiceItem;
import com.asset.salesforce.domain.InvoiceItemParent;
import com.asset.salesforce.domain.InvoiceService;
import com.asset.salesforce.domain.InvoiceSku;
import com.asset.salesforce.domain.InvoiceTax;
import com.asset.salesforce.domain.StockProduct;
import com.asset.salesforce.domain.StockSku;
import com.asset.salesforce.form.InvoiceTaxForm;
import com.asset.salesforce.form.StockCategoryForm;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.InventoryService;
import com.asset.salesforce.service.InvoiceOperationService;
import com.asset.salesforce.service.InvoiceTaxService;
import com.asset.salesforce.service.JoinRequestService;

@Controller
public class InvoicesController {

        @Autowired
        private InventoryService inventoryService;
        
        @Autowired
        private InvoiceTaxService invoiceTaxService;
        
        @Autowired 
        private ContactService contactService;
        
        
        @Autowired 
        private EmployeeService employeeService;
        
        @Autowired 
        private InvoiceOperationService invoiceOperationService;
        
        @Autowired
        private JoinRequestService joinRequestService;
        
        @Autowired
        private CalendarService calendarService;
        
        @RequestMapping(value="/new-invoice", method=RequestMethod.GET)
        public String getInvoice(Model model,HttpSession session){
        	if (SecurityUtils.getSubject().hasRole("invoiceAdd")){
        		if(null ==session.getAttribute("userDetails") ){
                    return "redirect:/s/login.html";
            }
            Employee employee = (Employee)session.getAttribute("userDetails");
            InvoiceTaxForm invoiceTaxForm = new InvoiceTaxForm();
            List<Integer> invoiceItems = new ArrayList<Integer>();
            invoiceItems.add(1);
            invoiceItems.add(2);
            invoiceItems.add(3);;
            List<StockSku> skus = inventoryService.getAllStockSKUs();
            List<InvoiceTax> taxes = invoiceTaxService.getAllTaxes();
            System.out.println(skus.size() + "++++++++++++++++++++++");
            List<Contact> contacts = new ArrayList<Contact>();
            contacts = contactService.getAllContactbyCompany(employee.getCompany().getCompanyName());
            ///contacts = contactService.getAllContactByEmpId(employee.getId());
            model.addAttribute("skus", skus);
            model.addAttribute("contacts", contacts);
            model.addAttribute("taxes", taxes);
            model.addAttribute("categoryForm", invoiceTaxForm);
            model.addAttribute("invoiceItems", invoiceItems);
            session.setAttribute("index", 0);
            joinRequestService.getJoinRquestNo(session, model);
            calendarService.getAppointmentEventsNo(session, model);
            calendarService.getCallEventssNo(session, model);
            return "new-invoice";
        	}
        	else{
        		return "accessDenied";
        	}
        }
        
        @RequestMapping(value="/new-invoice", method=RequestMethod.POST)
        public String postInvoice(Model model,HttpSession session,HttpServletRequest request,
                        @Valid @ModelAttribute("categoryForm") InvoiceTaxForm invoiceTaxForm,BindingResult result
//                       @RequestParam("contactedPerson") Integer contactId,
//                       @RequestParam("skuTrCount") Integer skuTrCount,
//                       @RequestParam("serviceTrCount") Integer serviceTrCount
                         ){
                if(null ==session.getAttribute("userDetails") ){
                        return "redirect:/s/login.html";
                }
                Employee employee = (Employee)session.getAttribute("userDetails");
                if(result.hasErrors()){
                	List<Integer> invoiceItems = new ArrayList<Integer>();
                    invoiceItems.add(1);
                    invoiceItems.add(2);
                    invoiceItems.add(3);;
                    List<StockSku> skus = inventoryService.getAllStockSKUs();
                    List<InvoiceTax> taxes = invoiceTaxService.getAllTaxes();
                    System.out.println(skus.size() + "++++++++++++++++++++++");
                    List<Contact> contacts = new ArrayList<Contact>();
                    contacts = contactService.getAllContactbyCompany(employee.getCompany().getCompanyName());
                    model.addAttribute("skus", skus);
                    model.addAttribute("contacts", contacts);
                    model.addAttribute("taxes", taxes);
                    model.addAttribute("categoryForm", invoiceTaxForm);
                    model.addAttribute("invoiceItems", invoiceItems);
                    session.setAttribute("index", 0);
                    joinRequestService.getJoinRquestNo(session, model);
                    calendarService.getAppointmentEventsNo(session, model);
                    calendarService.getCallEventssNo(session, model);
                    return "new-invoice";
                }
                
                Invoice invoice = new Invoice();
                
                if(invoiceTaxForm.getCode()!=null&& !invoiceTaxForm.getCode().equalsIgnoreCase("")){
                        invoice.setCode(invoiceTaxForm.getCode());
                }
                if(invoiceTaxForm.getContactedPersonId()!=null){
                        //Integer contactedPerson = Integer.parseInt(invoiceTaxForm.getContactedPerson());
                        invoice.setContact(contactService.getContactById(Integer.parseInt(invoiceTaxForm.getContactedPersonId())));
                }
                invoice.setOwner(employee);
                invoice.setDateCreated(new Date());
                Double discountTotal = 0.0;
                Double subTotal = 0.0; 
                 Integer skuId;
                 String code ;
                 String discount;
                 String price ;
                 String quantity ;
                //make calculations
                for(Integer i = 1;i<=Integer.parseInt(invoiceTaxForm.getServiceTrCount());i++){
                        if(request.getParameter("skuProduct"+i.toString()).equalsIgnoreCase("")){
                                break;
                        }
                        skuId=Integer.parseInt(request.getParameter("skuProduct"+i.toString()));
                         code = request.getParameter("skuName"+i.toString());
                         discount= request.getParameter("skuDiscount"+i.toString());
                         price = request.getParameter("skuPrice"+i.toString());
                         quantity = request.getParameter("skuQty"+i.toString());
                        Integer taxOne = Integer.parseInt(request.getParameter("skuTaxOne"+i.toString()));
                        Integer taxTwo = Integer.parseInt(request.getParameter("skuTaxTwo"+i.toString()));
                        
                        //InvoiceItemParent invoiceItemParent = new InvoiceItemParent();
                          Double discountVal = Double.parseDouble(discount) *  Double.parseDouble(price) / 100 ;
                          Double tax1Val = ( taxOne * Double.parseDouble(price) ) / 100 ;
                          Double tax2Val = (taxTwo * Double.parseDouble(price) ) / 100 ;
                          Double realItemPrice = Double.parseDouble(price) - discountVal + tax1Val + tax2Val;
                          Double linePrice = Double.parseDouble(quantity) * realItemPrice;
                          discountTotal+= (discountVal *  Double.parseDouble(quantity) * realItemPrice);
                          subTotal+= linePrice;
                                                
                }
                invoice.setTotalPrice(subTotal.toString());
                invoice.setDiscount(discountTotal.toString());
                invoiceOperationService.addInvoice(invoice);
                for(Integer i = 1;i<=Integer.parseInt(invoiceTaxForm.getServiceTrCount());i++){
                        if(request.getParameter("skuProduct"+i.toString()).equalsIgnoreCase("")){
                                break;
                        }
                        //InvoiceItemParent invoiceItemParent = new InvoiceItemParent();
                         skuId=Integer.parseInt(request.getParameter("skuProduct"+i.toString()));
                         code = request.getParameter("skuName"+i.toString());
                         discount= request.getParameter("skuDiscount"+i.toString());
                         price = request.getParameter("skuPrice"+i.toString());
                         quantity = request.getParameter("skuQty"+i.toString());
                        Integer taxOne = Integer.parseInt(request.getParameter("skuTaxOne"+i.toString()));
                        Integer taxTwo = Integer.parseInt(request.getParameter("skuTaxTwo"+i.toString()));
                    Double discountVal = Double.parseDouble(discount) *  Double.parseDouble(price) / 100 ;
                    Double tax1Val = ( taxOne * Double.parseDouble(price) ) / 100 ;
                    Double tax2Val = (taxTwo * Double.parseDouble(price) ) / 100 ;
                    Double realItemPrice = Double.parseDouble(price) - discountVal + tax1Val + tax2Val;
                    Double linePrice = Double.parseDouble(quantity) * realItemPrice;
                  discountTotal+= (discountVal *  Double.parseDouble(quantity) * realItemPrice);
                  subTotal+= linePrice;
                        String totalLine = request.getParameter("skuLineTotalHidden"+i.toString());
                        StockSku stockSku = inventoryService.getStockSKUById(skuId);
                        Integer quantityUpdated = Integer.parseInt(stockSku.getQuantity()) - Integer.parseInt(quantity);
                        stockSku.setQuantity(quantityUpdated.toString());
                        inventoryService.editStockSKU(stockSku);
                        InvoiceSku invoiceSku = new  InvoiceSku();
                        invoiceSku.setCode(code);
                        //invoiceSku.setComment("fgh");
                        invoiceSku.setDateCreated(new Date());
                        //invoiceSku.setDateModified(new Date());
                        //invoiceSku.setDescription("desc");
                        //invoiceSku.setFeedback("feedback");
                        invoiceSku.setFlag(false);
                        //invoiceSku.setInfo("info");
                        invoiceSku.setIsDeleted(false);
                        //invoiceSku.setName("name");
                        //invoiceSku.setNumber(12);
                        invoiceSku.setOwner(employee);
                        invoiceSku.setType("type");
                        invoiceSku.setPrice(price);
                        invoiceSku.setQuantity(quantity);
                        invoiceSku.setTotalPrice(linePrice.toString());
                        invoiceSku.setType("sku");      
                        invoiceSku.setStockSku(stockSku);
                        invoiceSku.setDiscount(discount);
//                      invoiceSku.setTaxOne(taxOne.toString());
//                      invoiceSku.setTaxTwo(taxTwo.toString());
                        invoiceOperationService.addInvoiceSku(invoiceSku);
                        InvoiceItem invoiceItem = new InvoiceItem();
                        invoiceItem.setInvoice(invoice);
                        invoiceItem.setInvoiceItemParent(invoiceSku);
                        invoiceOperationService.addInvoiceItem(invoiceItem);
                                                
                }
                
                for(Integer i = 1;i<=Integer.parseInt(invoiceTaxForm.getServiceTrCount());i++){
                        if(request.getParameter("serviceProduct"+i.toString()).equalsIgnoreCase("")){
                                break;
                        }
                        String name= request.getParameter("serviceProduct"+i.toString());
                        String info = request.getParameter("serviceInfo"+i.toString());
                        discount = request.getParameter("serviceDiscount"+i.toString());
                    price = request.getParameter("servicePrice"+i.toString());
                        quantity = request.getParameter("serviceQty"+i.toString());
                        System.out.println("******taxone,taxtwo******" + request.getParameter("serviceTaxOne"+i.toString()) + "**" + request.getParameter("serviceTaxTwo"+i.toString()));

                        System.out.println("******taxone******" + Integer.parseInt(request.getParameter("serviceTaxOne"+i.toString())));
                        Integer taxOne = Integer.parseInt(request.getParameter("serviceTaxOne"+i.toString()));
                        Integer taxTwo = Integer.parseInt(request.getParameter("serviceTaxTwo"+i.toString()));
                        String lineTotal = request.getParameter("serviceLineTotalHidden"+i.toString());
                        InvoiceService invoiceService = new  InvoiceService();
                        invoiceService.setDateCreated(new Date());
                        //invoiceSku.setDateModified(new Date());
                        //invoiceSku.setDescription("desc");
                        //invoiceSku.setFeedback("feedback");
                        invoiceService.setFlag(false);
                        invoiceService.setInfo(info);
                        invoiceService.setIsDeleted(false);
                        invoiceService.setName(name);
                        //invoiceSku.setNumber(12);
                        invoiceService.setOwner(employee);
                        invoiceService.setCostPerHour(price);
                        invoiceService.setHours(quantity);
                        invoiceService.setTotalCost(lineTotal);
                        invoiceService.setType("service");      
                        invoiceService.setDiscount(discount);
//                      invoiceService.setTaxOne(taxOne.toString());
//                      invoiceService.setTaxTwo(taxTwo.toString());
                        invoiceService.setTotalCost(lineTotal);
                        invoiceOperationService.addInvoiceService(invoiceService);
                        InvoiceItem invoiceItem = new InvoiceItem();
                        invoiceItem.setInvoice(invoice);
                        invoiceItem.setInvoiceItemParent(invoiceService);
                        invoiceOperationService.addInvoiceItem(invoiceItem);
                }
                joinRequestService.getJoinRquestNo(session, model);
                calendarService.getAppointmentEventsNo(session, model);
                calendarService.getCallEventssNo(session, model);
                return "redirect:/s/invoices";
        }
        
        @RequestMapping(value="/invoiceLine", method=RequestMethod.GET)
        public String getInvoiceLine(Model model,HttpSession session){
                if(null ==session.getAttribute("userDetails") ){
                        return "redirect:/s/login.html";
                }
                List<StockSku> skus = inventoryService.getAllStockSKUs();
                model.addAttribute("skus", skus);
                joinRequestService.getJoinRquestNo(session, model);
				calendarService.getAppointmentEventsNo(session, model);
				calendarService.getCallEventssNo(session, model);
                return "invoiceLine";
        }       
        
        @RequestMapping(value="/invoiceServiceLine", method=RequestMethod.GET)
        public String getInvoiceServiceLine(Model model,HttpSession session){
                if(null ==session.getAttribute("userDetails") ){
                        return "redirect:/s/login.html";
                }
                joinRequestService.getJoinRquestNo(session, model);
                calendarService.getAppointmentEventsNo(session, model);
                calendarService.getCallEventssNo(session, model);
                return "invoiceServiceLine";
        }       
        
        @RequestMapping(value="/view-invoice", method=RequestMethod.GET)
        public String getInvoiceView(Model model,HttpSession session,
                        @RequestParam(value="id",required=false)Integer id){
        	if (SecurityUtils.getSubject().hasRole("invoiceView")){
        		if(null ==session.getAttribute("userDetails") ){
                    return "redirect:/s/login.html";
            }
            Invoice invoice = invoiceOperationService.getInvoiceById(id);
            //List<InvoiceItem> invoiceItems = invoiceOperationService.getInvoiceItemsByInvoice(id);
            List<InvoiceSku> invoiceSkus = invoiceOperationService.getInvoiceSkusByInvoice(id);
            List<InvoiceService> invoiceServices = invoiceOperationService.getInvoiceServicesByInvoice(id);
            model.addAttribute("invoice", invoice);
            //model.addAttribute("invoiceItems", invoiceItems);
            model.addAttribute("invoiceSkus", invoiceSkus);
            model.addAttribute("invoiceServices", invoiceServices);
            joinRequestService.getJoinRquestNo(session, model);
            calendarService.getAppointmentEventsNo(session, model);
            calendarService.getCallEventssNo(session, model);
            return "view-invoice";
        	}
        	else{
        		return "accessDenied";
        	}
        }       
        
        @RequestMapping(value="/invoices", method=RequestMethod.GET)
        public String getInvoices(Model model,HttpSession session){
                if(null ==session.getAttribute("userDetails") ){
                        return "redirect:/s/login.html";
                }
                Employee employee = (Employee)session.getAttribute("userDetails");
                List<Invoice> invoiceList = invoiceOperationService.getAllInvoicesByEmp(employee.getId());
                System.out.println(invoiceList.size() + "**************************************");
                model.addAttribute("invoiceList", invoiceList);
                joinRequestService.getJoinRquestNo(session, model);
                calendarService.getAppointmentEventsNo(session, model);
                calendarService.getCallEventssNo(session, model);
                return "invoices";
        }
        
        
        
}
